package com.ieng.kican.modules.security.rest;

import com.ieng.kican.common.exception.VerifyException;
import com.ieng.kican.common.http.MR;
import com.ieng.kican.common.http.use.ActionR;
import com.ieng.kican.common.utils.IUtil;
import com.ieng.kican.modules.security.core.annotaion.AnonymousAuthorize;
import com.ieng.kican.modules.security.domain.LoginAction;
import com.ieng.kican.modules.security.domain.Token;
import com.ieng.kican.modules.security.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthorizationController {
    @Autowired
    private AuthorizationService authorizationService;

    @AnonymousAuthorize
    @PostMapping("/sign-in")
    public MR<?> doLogin(@Validated @RequestBody LoginAction action) {
        boolean flag = authorizationService.verify(action.getUuid(), action.getCode());

        if (!flag) throw new VerifyException("验证码错误");

        Token token = authorizationService.login(action.getUsername(), action.getPassword());

        if (IUtil.isNotObject(token)) {
            return ActionR.success(token);
        }

        return ActionR.error("登录失败");
    }

    @AnonymousAuthorize
    @GetMapping("/captcha")
    public MR<?> doCaptcha() {
        return ActionR.success(authorizationService.generateCode());
    }


}
